package org.jeecg.modules.online.desform.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecgframework.poi.handler.impl.ExcelDataHandlerDefaultImpl;
import org.jeecgframework.poi.util.PoiPublicUtil;

import java.util.HashMap;
import java.util.Map;

/** Excel 导入 处理类 */
public class DesformExcelHandler extends ExcelDataHandlerDefaultImpl {

    public static final String MAIN_KEY = "$mainTable$";
    public static final String SUB_KEY = "$subTable$";

    private Map<String, JSONObject> fieldMap;

    public DesformExcelHandler(JSONArray dataList) {
        fieldMap = convertDate(dataList);
    }

    private Map<String, JSONObject> convertDate(JSONArray dataList) {
        Map<String, JSONObject> maps = new HashMap<>();

        DesformUtils.recursiveAllWidget(dataList, (type, item, parent) -> {
            // 过滤
            if (!DesformUtils.isNotDataWidget(type)) {
                maps.put(item.getString("name"), item);
            }
        });

        return maps;
    }

    @Override
    public void setMapValue(Map<String, Object> map, String originKey, Object value) {
        if (value instanceof Double) {
            map.put(getRealKey(originKey), PoiPublicUtil.doubleToString((Double) value));
        } else {
            map.put(getRealKey(originKey), value == null ? "" : value.toString());
        }
    }

    private String getRealKey(String originKey) {
        if (fieldMap.containsKey(originKey)) {
            //主表字段
            return MAIN_KEY + fieldMap.get(originKey).get("model");
        }
        //子表字段
        return SUB_KEY + originKey;
    }

}